package com.bridgetek.carlauncher.fragment;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import com.bridgetek.carlauncher.Constants;
import com.bridgetek.carlauncher.HttpRequest;
import com.bridgetek.carlauncher.MainActivity;
import com.bridgetek.carlauncher.R;
import com.bridgetek.carlauncher.service.LocationService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class FirstFragment extends Fragment implements View.OnClickListener {
    private View mContentView;
    private MainActivity mActivity;
    private boolean gaoDeMap, baiDuMap;
    private ResolveInfo baiduResolveInfo, gaodeResolveInfo;

    private String mDate = "", mCity = "", mTemp = "", mWeek = "";
    private TextView mWeatherTv, mDateTv, mWeekTv;

    private PackageManager mPackageManager;
    private LocationBroadcastReceiver weatherReceiver;


    public static FirstFragment newInstance() {
        Bundle args = new Bundle();
        FirstFragment fragment = new FirstFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_one_lay, container, false);
        return mContentView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
        initData();
    }


    private void initView() {
        mActivity = (MainActivity) getActivity();
        mWeatherTv = (TextView) mContentView.findViewById(R.id.tv_weather);
        mWeekTv = (TextView) mContentView.findViewById(R.id.tv_week);
        mDateTv = (TextView) mContentView.findViewById(R.id.tv_date);
    }

    private void initListener() {
        mContentView.findViewById(R.id.ll_weather).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_gps).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_yika_online).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_car_record).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_speed_warning).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_bluetooth).setOnClickListener(this);
    }

    private void initData() {
        getLocation();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_weather:
                break;
            case R.id.tv_gps:
                openGpsNavigation();
                break;
            case R.id.tv_yika_online:
//                openYiKa();
                break;
            case R.id.tv_car_record:
                openDriveRecord();
                break;
            case R.id.tv_speed_warning:
//                openSpeedWarning();
                break;
            case R.id.tv_bluetooth:
                openBluetoothPhone();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mActivity != null) {
            mActivity.unregisterReceiver(weatherReceiver);

            Intent iService = new Intent(mActivity, LocationService.class);
            iService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mActivity.stopService(iService);
        }
    }

    /**
     * gps导航
     */
    private void openGpsNavigation() {
        if (isMapAppExist()) {
            if (baiDuMap && gaoDeMap) {
                showMapSelectView();
            } else if (gaoDeMap) {
                openApp(gaodeResolveInfo);
            } else {
                openApp(baiduResolveInfo);
            }
        } else {
            if (mActivity != null) {
                Toast.makeText(mActivity, mActivity.getString(R.string.gps_hint), Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 翼卡在线
     */
    private void openYiKa() {
        ResolveInfo resolveInfo = getResolveInfo(Constants.YIKA_PACKAGE);
        if (resolveInfo != null) {
            openApp(resolveInfo);
        } else {
            Toast.makeText(mActivity, mActivity.getString(R.string.yika_hint), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 行车记录
     */
    private void openDriveRecord() {
        ResolveInfo resolveInfo = getResolveInfo(Constants.CAR_RECORDER_PACKAGE);
        if (resolveInfo != null) {
            openApp(resolveInfo);
        } else {
            Toast.makeText(mActivity, mActivity.getString(R.string.recorder_hint), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 测速预警
     */
    private void openSpeedWarning() {
        ResolveInfo resolveInfo = getResolveInfo(Constants.SPEED_WARNING_PACKAGE);
        if (resolveInfo != null) {
            openApp(resolveInfo);
        } else {
            Toast.makeText(mActivity, mActivity.getString(R.string.speed_warning_hint), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 蓝牙电话
     */
    private void openBluetoothPhone() {
        ResolveInfo resolveInfo = getResolveInfo(Constants.BLUETOOTH_CALL_PACKAGE);
        if (resolveInfo != null) {
            openApp(resolveInfo);
        } else {
            Toast.makeText(mActivity, mActivity.getString(R.string.bluetooth_hint), Toast.LENGTH_SHORT).show();
        }
    }


    private void getLocation() {
        if (mActivity != null) {

            if (!isConnected(mActivity)) {
                Toast.makeText(mActivity, mActivity.getString(R.string.net_disconnect), Toast.LENGTH_SHORT).show();
            }

            // 注册广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constants.LOCATION_ACTION);
            weatherReceiver = new LocationBroadcastReceiver();
            mActivity.registerReceiver(weatherReceiver, filter);

            // 启动服务
            Intent intent = new Intent();
            intent.setClass(mActivity, LocationService.class);
            mActivity.startService(intent);
        }
    }


    /**
     * 调用安装的地图三方应用 应用包名, com.autonavi.amapauto--高德(车机), com.baidu.BaiduMap--百度,
     */
    public boolean isMapAppExist() {
        gaoDeMap = baiDuMap = false;

        if (mActivity != null) {

            //应用过滤条件
            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            mPackageManager = mActivity.getPackageManager();
            List<ResolveInfo> mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);

            for (ResolveInfo res : mAllApps) {
                //该应用的包名和主Activity
                String pkg = res.activityInfo.packageName;
                if (pkg.contains(Constants.GAODE_AMAP_PACKAGE)) {
                    gaodeResolveInfo = res;
                    gaoDeMap = true;
                } else if (pkg.contains(Constants.BAIDU_AMAP_PACKAGE)) {
                    baiduResolveInfo = res;
                    baiDuMap = true;
                }
            }
        }

        return gaoDeMap || baiDuMap;
    }

    /**
     * 打开应用
     *
     * @param res
     */
    private void openApp(ResolveInfo res) {
        if (res != null) {
            String pkg = res.activityInfo.packageName;
            String cls = res.activityInfo.name;
            ComponentName component = new ComponentName(pkg, cls);
            Intent intent = new Intent();
            intent.setComponent(component);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mActivity.startActivity(intent);
        }

    }

    /**
     * 显示选择地图提示框
     */
    private void showMapSelectView() {
        MapDialog dialog = new MapDialog(mActivity, R.style.hint_dialog);
        dialog.show();
    }


    public class MapDialog extends Dialog {

        private ImageView mBaiduIv, mGaodeIv;
        private TextView mBaiduTxt, mGaodeTxt;

        public MapDialog(Context context, int theme) {
            super(context, theme);
            setContentView(R.layout.map_dialog_lay);
            mBaiduIv = (ImageView) findViewById(R.id.iv_baidu);
            mGaodeIv = (ImageView) findViewById(R.id.iv_gaode);

            mBaiduTxt = (TextView) findViewById(R.id.tv_baidu);
            mGaodeTxt = (TextView) findViewById(R.id.tv_gaode);

            mGaodeIv.setImageDrawable(gaodeResolveInfo.loadIcon(mPackageManager));
            mGaodeTxt.setText(gaodeResolveInfo.loadLabel(mPackageManager));
            mBaiduIv.setImageDrawable(baiduResolveInfo.loadIcon(mPackageManager));
            mBaiduTxt.setText(baiduResolveInfo.loadLabel(mPackageManager));

            findViewById(R.id.ll_gaode).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dismiss();
                    openApp(gaodeResolveInfo);
                }
            });

            findViewById(R.id.ll_baidu).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    dismiss();
                    openApp(baiduResolveInfo);
                }
            });
        }
    }


    private class LocationBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (!intent.getAction().equals(Constants.LOCATION_ACTION)) return;
            if (mActivity != null) {
                String adCode = intent.getStringExtra(Constants.CITY_ADCODE);
                getWeatherInfo(adCode);
            }

        }
    }

    /**
     * 判断应用是否存在,若存在则获取其ResolveInfo对象
     *
     * @param pack
     * @return
     */
    private ResolveInfo getResolveInfo(String pack) {
        if (mActivity != null) {
            //应用过滤条件
            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            PackageManager mPackageManager = mActivity.getPackageManager();
            List<ResolveInfo> mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);

            for (ResolveInfo res : mAllApps) {
                //该应用的包名和主Activity
                if (res.activityInfo.packageName.equals(pack)) {
                    return res;
                }
            }
        }
        return null;
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {

            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }


    /*****************************start*******************************/

    /**
     * 获取天气
     *
     * @param adCode
     */
    public void getWeatherInfo(String adCode) {
        if (adCode != null) {
            final String url = "http://restapi.amap.com/v3/weather/weatherInfo?city=" + adCode + "&extensions=all&key=7dba06b0763d8dd433e5d1806fd4a808";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String response = HttpRequest.get(url).body();
                        AnalysisJson(response);
                        if (mActivity != null) {
                            mActivity.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    StringBuilder sb = new StringBuilder();
                                    sb.append(mCity).append(mActivity.getString(R.string.weather)).append(" ").append(mTemp);
                                    mWeatherTv.setText(sb.toString());
                                    mDateTv.setText(splitDate(mDate));
                                    mWeekTv.setText(getWeekString(mWeek));
                                }

                            });
                        }
                    } catch (Exception exception) {
                        Log.d("WTF", "run: " + exception.toString());
                    }
                }
            }).start();
        }

    }

    /**
     * 解析天气JSON
     *
     * @param response
     */
    private void AnalysisJson(String response) {
        try {
            JSONObject object = new JSONObject(response);
            String status = object.getString("status");
            if (status.equals("1")) {
                JSONArray forecastArray = object.getJSONArray("forecasts");
                if (forecastArray != null) {
                    JSONObject forecastObj = forecastArray.getJSONObject(0);
                    if (forecastObj != null) {
                        mCity = forecastObj.getString("city");
                        JSONArray castsArray = forecastObj.getJSONArray("casts");
                        if (castsArray != null) {
                            JSONObject castsObj = castsArray.getJSONObject(0);
                            if (castsObj != null) {
                                mDate = castsObj.getString("date");
                                mWeek = castsObj.getString("week");
                                StringBuilder sb = new StringBuilder();
                                sb.append(castsObj.getString("nighttemp"));
                                sb.append("~");
                                sb.append(castsObj.getString("daytemp"));
                                if (mActivity != null) {
                                    sb.append(mActivity.getString(R.string.temperature));
                                }
                                mTemp = sb.toString();
                            }
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param date 2016-10-09
     * @return 2016年10月09日
     */
    private String splitDate(String date) {
        if (date != null && date.contains("-")) {
            String[] strings = date.split("-");
            if (3 == strings.length) {
                StringBuilder sb = new StringBuilder();
                sb.append(strings[0]);
                sb.append(mActivity.getString(R.string.year));
                sb.append(strings[1]);
                sb.append(mActivity.getString(R.string.month));
                sb.append(strings[2]);
                sb.append(mActivity.getString(R.string.date));

                return sb.toString();
            }
        }
        return date;
    }

    /**
     * @return 星期一
     */
    private String getWeekString(String w) {
        String week = "";
        if (w != null) {
            switch (w) {
                case "1":
                    week = mActivity.getString(R.string.Mon);
                    break;
                case "2":
                    week = mActivity.getString(R.string.Tue);
                    break;
                case "3":
                    week = mActivity.getString(R.string.Wed);
                    break;
                case "4":
                    week = mActivity.getString(R.string.Thurs);
                    break;
                case "5":
                    week = mActivity.getString(R.string.Fri);
                    break;
                case "6":
                    week = mActivity.getString(R.string.Sat);
                    break;
                case "7":
                    week = mActivity.getString(R.string.Sun);
                    break;
            }
        }
        return week;
    }

    /*****************************end*******************************/

}
